//app.js

const Base64 = require('./lib/aliyun/lib/base64.js');
import ENVIRONMENT_CONFIG from './config/envConfig.js'
import PAGE_CONFIG from './config/pageConfig.js'
import createStore from './redux/createStore.js';
import reducer from './store/reducer.js';
import serviceAddress from './utils/serverAddress.js'
import agreementUrl from './utils/argumentUrl.js'
const store = createStore(reducer) // redux store
App({
    onLaunch: function() {

        // let systemInfo = wx.getSystemInfoSync();
        // this.globalData.videoContainerSize = {
        //     width: systemInfo.windowWidth,
        //     height: systemInfo.windowHeight
        // }
        this.globalData.isPushBeCallPage = false
        // 展示本地存储能力
        // var logs = wx.getStorageSync('logs') || []
        // logs.unshift(Date.now())
        // wx.setStorageSync('logs', logs)

        this.getServerToken();


        // 登录
        wx.login({
            success: res => {
                // 发送 res.code 到后台换取 openId, sessionKey, unionId
                this.globalData.code = res.code;
                // console.log(JSON.stringify(res));
            }
        });
        let that = this;
        // 获取用户信息
        wx.getSetting({
            success: res => {
                console.log("success:" + JSON.stringify(res))
                if (res.authSetting['scope.userInfo']) {
                    // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
                    wx.getUserInfo({
                        success: res => {
                            // 可以将 res 发送给后台解码出 unionId
                            // console.log(res);
                            this.globalData.userInfo = res.userInfo;
                            res.userInfo.iv = res.iv;
                            res.userInfo.encryptedData = res.encryptedData;
                            // console.log(res);
                            if (this.globalData.token) {
                                this.userLogin(res.userInfo, function(info) {
                                    if (that.userInfoReadyCallback) {
                                        that.userInfoReadyCallback(res)
                                    }
                                });
                            }
                            // this.globalData.signature = res.signature;
                            // this.globalData.encryptedData = res.encryptedData;
                            // this.globalData.iv = res.iv;
                            // this.globalData.isLogin = true;
                            // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
                            // 所以此处加入 callback 以防止这种情况
                            // this.getApproveUser();
                        }
                    })
                }
            },
            fail: function(res) {
                console.log("fail:" + JSON.stringify(res))
            },
            complete: function(res) {},
        });
    },
    checkLoactionAuth(){
        let that = this;
        wx.getSetting({
            success: (res) => {
                // res.authSetting['scope.userLocation'] == undefined    表示 初始化进入该页面
                // res.authSetting['scope.userLocation'] == false    表示 非初始化进入该页面,且未授权
                // res.authSetting['scope.userLocation'] == true    表示 地理位置授权
                if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
                    wx.showModal({
                        title: '请求授权当前位置',
                        content: '需要获取您的地理位置，请确认授权',
                        success: function (res) {
                            if (res.cancel) {
                                wx.showToast({
                                    title: '拒绝授权',
                                    icon: 'none',
                                    duration: 1000
                                })
                            } else if (res.confirm) {
                                wx.openSetting({
                                    success: function (dataAu) {
                                        if (dataAu.authSetting["scope.userLocation"] == true) {
                                            that.getWXLocation();
                                        } else {
                                            wx.showToast({
                                                title: '授权失败',
                                                icon: 'none',
                                                duration: 1000
                                            })
                                        }
                                    }
                                })
                            }
                        }
                    })
                } else if (res.authSetting['scope.userLocation'] == undefined) {
                    //调用wx.getLocation的API
                    that.getWXLocation();
                }
                else {
                    //调用wx.getLocation的API
                    that.getWXLocation();
                }
            }
        })
    },
    //保存地理位置信息到服务器
    saveUserLocate(data){
        let that = this;
        console.log("saveUserLocate parmas" , data);
        wx.request({
            url: that.globalData.serverAddress.saveUserLocate,
            method: 'POST',
            data: data,
            header: {
                'Authorization': "Bearer " + that.globalData.token
            },
            success: function (res) { 
                console.log("saveUserLocate response" , res)
                if (res.statusCode == 200 && res.data.CodeStatus == 20000) {
                    if (that.locateReadyCallback) {
                        that.locateReadyCallback(res.data.BodyContent.City)
                    }
                }
            },
            fail: function (res) {console.log("saveUserLocate fail" + JSON.stringify(res));}
        })
    },
    //保存用户积分
    saveCredit(func) {
        let that = this;
        wx.request({
            url: that.globalData.serverAddress.saveCredit,
            method: 'POST',
            header: {
                'Authorization': "Bearer " + that.globalData.token
            },
            data: {
                "UserInfoId": that.userInfo.Id,
                "DetailType": 1,
                "CreditType": that.globalData.creditType
            },
            success: function (res) {
                console.log("saveCredit response", res);
                if (res.statusCode == 200 && res.data.CodeStatus == 20000) {
                    let body = res.data.BodyContent;
                    if(func){
                        func(body.Count)
                    }
                }
            },
            fail: function (res) {
                console.log("saveCredit fail", res);
            }
        });
    },
    getWXLocation(){
        let that = this;
        wx.getLocation({
            type: 'wgs84',
            success(res) {
                let data = {
                    UserInfoId: that.userInfo.Id,
                    longitude: res.longitude,
                    latitude: res.latitude
                }
                that.saveUserLocate(data);

            }
        })
    },
    getServerToken() {
        //从服务器获取token
        let that = this;
        let tokenKey = that.globalData.appKey + ":" + that.globalData.appSecret;
        let tokenKey64 = Base64.encode(tokenKey);
        let authHeader = 'Basic ' + tokenKey64;
        // console.log(tokenKey);
        // console.log(authHeader);
        let _data = {
            grant_type: 'client_credentials'
        }
        wx.request({
            url: that.globalData.serverAddress.getTokenUrl,
            method: 'POST',
            data: 'grant_type=client_credentials',
            header: {
                'Content-Type': 'application/x-www-form-urlencod',
                'Authorization': authHeader
            },
            success: function(res) {
                if (res.statusCode == 200) {
                    that.globalData.token = res.data.access_token;
                    // console.log(res.data.access_token)
                    if (that.tokenReadyCallback != null) {
                        that.tokenReadyCallback();
                    }
                }

            },
            fail: function(res) {
                console.log("fail" + JSON.stringify(res));
            }
        })
    },
    userLogin: function(userInfo, _success) {
        // console.log(userInfo);
        wx.showLoading({
            title: '正在登录...',
            mask: true
        })
        let that = this;
        wx.request({
            url: that.globalData.serverAddress.login,
            data: {
                Code: that.globalData.code,
                NickName: userInfo.nickName,
                Gender: userInfo.gender,
                ProfilePicture: userInfo.avatarUrl,
                EncryptedData: userInfo.encryptedData,
                Iv: userInfo.iv
            },
            header: {
                'Authorization': "Bearer " + that.globalData.token
            },
            method: 'POST',
            success: function(res) {
                if (res.statusCode == 200 && res.data.CodeStatus == 20000) {
                    that.globalData.isLogin = true;
                    that.userInfo = res.data.BodyContent;
                    if (that.userInfo.MobileNumber) {
                        that.globalData.isBindPhone = true;
                    }
                    console.log("userLogin" , res);
                    if (_success) {
                        // console.log(_success);
                        _success(res.data.BodyContent);
                    }
                    that.checkLoactionAuth();
                }
            },
            fail: function(res) {
                console.log("login fail：" + res);
            },
            complete: function(res) {
                wx.hideLoading();
            },
        })
    },
    globalData: {
        emitter:null,
        enterpriseInfo:null,
        resumeInfo:null,
        editJobInfo:{},
        userInfo: null,
        ENVIRONMENT_CONFIG,
        PAGE_CONFIG,
        serverAddress: serviceAddress,
        serverItemTypes: null,
        token: '',
        appKey: 'client_fsdiUri3isos3Ios',
        appSecret: 'Jdiiw3Niweo20924Iidt34gnfiqji2889231s',
        code: '',
        isLogin: false,
        isBindPhone: false,
        agreementUrl,
        appDownloadUrl: 'https://www.51xj.mobi/M/Download',
        serviceContent:'',
        globalWebUrl:'',
        serviceInfo:{},
        enterpriseInfo:{},
        creditType:4
    },
    userInfo: null,
    store
})